import { constantRoutes } from '@/router'
import LRLayout from '@/layout/LRLayout'
import UDLayout from '@/layout/UDLayout'
import { methodGetApi } from '@/api/publicApi'
const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
    cateRouter: [],
    cateValue: '',
    cateLabel: null,
    originalRouters: {},
    topMenuRouter: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_TOPMENUROUTER: (state, topMenuRouter) => {
      state.topMenuRouter = topMenuRouter
    },
    SET_ORIGINAL_ROUTES: (state, routes) => {
      state.originalRouters = routes
    },
    SET_CATEROUTES: (state, cate) => {
      state.cateRouter = cate
    },
    SET_CATEVALUE: (state, cateValue) => {
      state.cateValue = cateValue
    },
    SET_CATELABEL: (state, label) => {
      state.cateLabel = label
    },
    SET_SIDEBAR_ROUTERS: (state, curItem) => {
      const newCurItem = curItem ? JSON.parse(JSON.stringify(curItem.router)) : ''
      // state.sidebarRouters = newCurItem
      // 过滤 左右布局的路由
      state.sidebarRouters = newCurItem.filter((route, index, array) => {
        // 返回 true 或 false，决定元素是否保留
        return route.layoutType === 'LRLayout'
      })
    }
  },
  actions: {
    setSideBar({ state, commit, dispatch }, to) {
      if (!state.originalRouters) {
        commit('SET_SIDEBAR_ROUTERS', { router: [] })
        return false
      }
      const curItem = getParentRouteWithChildren(state.originalRouters, to.name)
      // 如果没有curItem,当前页面为本地配置页面,根据本地页面中的meta.type判断对应sidebar
      if (!curItem) {
        // 如果没有meta.type 则为项目工程管理sidebar
        if (!to.meta.type) {
          commit('SET_SIDEBAR_ROUTERS', state.originalRouters['SYSTEM_CENTER'])
          commit('SET_CATELABEL', '系统管理')
        } else {
          commit('SET_SIDEBAR_ROUTERS', state.originalRouters[to.meta.type])
          commit('SET_CATELABEL', state.originalRouters[to.meta.type].label)
        }
        return false
      } else {
        if (state.cateLabel != curItem.label) {
          dispatch('tagsView/delAllVisitedViews')
          commit('SET_SIDEBAR_ROUTERS', curItem)
          commit('SET_CATELABEL', curItem.label)
        }
      }
    },
    getCateRouter({ commit }) {
      return new Promise(resolve => {
        methodGetApi('/models/getAll').then(res => {
          commit('SET_CATEROUTES', res.data)
          resolve(res.data)
        })
      })
    },
    // 生成路由
    GenerateRoutes({ commit }, menuKey) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        const data = {
          menuKey: menuKey
        }
        methodGetApi('/getRouters', data).then(res => {
          if (JSON.stringify(res.data) == '{}') {
            commit('SET_ORIGINAL_ROUTES', null)
          } else {
            commit('SET_ORIGINAL_ROUTES', res.data)
          }

          // 设置项目信息页面为固定tag
          // res.data.AGENT_BUILD_CENTER.router[0].children[0].meta.affix = true

          const allRouters = []
          for (const key in res.data) {
            const ele = res.data[key]
            allRouters.push(...ele.router)
          }
          const rdata = JSON.parse(JSON.stringify(allRouters))
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', rewriteRoutes)
          resolve(rewriteRoutes)
        })
      })
    },
    // 导航栏生成
    getTopMenu({ commit }, data) {
      return new Promise(resolve => {
        const url = '/system/menu/getTopMenu'
        methodGetApi(url).then(res => {
          commit('SET_TOPMENUROUTER', res.data.router)
          resolve(res.data.router)
        })
      })
    },
    // 更改状态
    updateTopMenu({ commit }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_TOPMENUROUTER', data)
        resolve(data)
      })
    },
    deleteRoutes({ commit }) {
      commit('SET_ROUTES', '')
      commit('SET_TOPMENUROUTER', '')
      commit('SET_ORIGINAL_ROUTES', '')
      commit('SET_CATEROUTES', '')
      commit('SET_CATEVALUE', '')
      commit('SET_CATELABEL', '')
      commit('SET_SIDEBAR_ROUTERS', { router: [] })
    }
  }
}

// 根据某一个页面找到父节点所有数据
function getParentRouteWithChildren(routers, name) {
  let parentItem = ''
  let childrenItem = ''
  for (const key in routers) {
    const item = routers[key]
    if (childrenItem) {
      break
    }
    if (item.router.length > 0 && !childrenItem) {
      getChildren(item.router, name, item)
    }
  }

  function getChildren(arr, name, item) {
    if (childrenItem) {
      return false
    }
    for (let i = 0; i < arr.length; i++) {
      const ele = arr[i]
      if (ele.name && ele.name == name) {
        childrenItem = ele
        parentItem = item
        break
      }
      if (!childrenItem && ele.children) {
        getChildren(ele.children, name, item)
      }
    }
  }

  return parentItem
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.parentPath) {
      route.meta.parentPath = route.parentPath
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.layoutType === 'LRLayout') {
        route.component = LRLayout
      } else if (route.layoutType === 'UDLayout') {
        route.component = UDLayout
      } else {
        // console.log(route.component)
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  let children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
